class Admin::ProductsController < Admin::AdminController
  before_action :find_innoaward
  skip_before_action :store_previous_url, only: [:search, :approve, :create, :update, :destroy]

  def index
    @products = @innoaward.products
    @products = @products.with_status(params[:status]) if params[:status]
    @products = @products.order(created_at: :desc).page params[:page]
    gon.products = @products.map{|pro| pro.as_my_json(@innoaward.id)}
    gon.innoaward_id = @innoaward.id
  end

  def search
    @products = Product.search(params[:query])
    products = @products.map{|pro| pro.as_my_json(@innoaward.id)}
    res = {products: products}
    render json: res
  end

  def approve
    @product = Product.find(params[:id])
    @product.update(status: params[:status])
    render json: @product.as_my_json(@innoaward.id)
  end

  def new
    @product = Product.new
  end

  def create
    innoaward = Innoaward.find_by_id(params[:innoaward_id])
    @product = Product.new(product_params)
    if @product.save
      InnoawardsProduct.create(innoaward_id: innoaward.id, product_id: @product.id)
      redirect_to admin_innoaward_products_path(@innoaward)
    else
      render :new
    end
  end

  def show
    @product = Product.find(params[:id])
  end

  def edit
    @product = Product.find(params[:id])
  end

  def update
    @product = Product.find(params[:id])
    if @product.update(product_params)
      redirect_to admin_innoaward_products_path(@innoaward)
    else
      render :edit
    end
  end

  def destroy
    @product = Product.find(params[:id])
    @product.destroy
    redirect_to admin_innoaward_products_path(@innoaward)
  end

  private

  def product_params
    recommended_platform = params[:product][:recommended_platform]
    params[:product][:recommended_platform] = recommended_platform.split(',').map(&:strip) if (params[:product] && (recommended_platform.is_a? String))
    params
      .require(:product)
      .permit(:name, :logo, :logo_cache, :summary, :description, :url, {screenshots: []},
              :published_at, :weibo, :wechat, :category, {recommended_platform: []},
              :c_name, :c_corp, :c_position, :c_corp_addr, :c_email, :c_mobile, :evaluation)
  end

  def find_innoaward
    @innoaward = Innoaward.find(params[:innoaward_id])
  end
end
